const express = require('express')
const models = require('../models')
const router = express.Router()
const { success, error } = require('../utils/message')

// 分类列表
router.get('/', async function (req, res, next) {
    const categories = await models.Category.findAll({
        order: [
            ['sort', 'ASC'],
            ['children', 'sort', 'ASC'],
        ],
        where: { parentId: 0 },
        include: [{
            model: models.Category,
            as: 'children',
        }],
    })

    success(res, '查询成功', { categories })
})

// 分类内页，对应的商品列表
router.get('/:id', async function (req, res, next) {
    const category = await models.Category.findByPk(req.params.id)
    if (!category) {
        return error(res, '当前分类不存在')
    }

    const products = await models.Product.findAll({
        order: [
            ['id', 'DESC']
        ],
        where: {
            categoryId: req.params.id,
            onsale: true
        },
    })

    success(res, '查询成功', { category, products })
})

module.exports = router
